<?php

namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StorePermissionsRequest;
use App\Http\Requests\Admin\UpdatePermissionsRequest;
use App\Http\Models\Admin\Permission_;
use App\Http\Models\Admin\ClassifyPermissions;
use App\Http\Models\Admin\PermissionsDetails;
use Validator;

class PermissionsController extends Controller
{
    /**
     * Display a listing of Permission.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (! Gate::allows('watch power')) {
            return abort(401);
        }
        $permission= new Permission_();
        $permissions = $permission->with(['hasDetails','classify_belongsToMany'])->get();
        
        return view('admin.manage.permissions.index', compact('permissions'));
    }

    /**
     * Show the form for creating new Permission.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if (! Gate::allows('create power')) {
            return abort(401);
        }
        $classify = ClassifyPermissions::where(array('parent_id'=>0))->orderBy('rank','DESC')->with(['classifyHasMany'])->get();

        return view('admin.manage.permissions.create',compact('classify'));
    }

    /**
     * Store a newly created Permission in storage.
     *
     * @param  \App\Http\Requests\StorePermissionsRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StorePermissionsRequest $request)
    {
        if (! Gate::allows('create power')) {
            return abort(401);
        }
        $this->validator($request->all())->validate();
        $per_arr=$request->all();
        $classify_ids=$per_arr['classify'];
        unset($per_arr['classify'],$per_arr['explain']);

        $permission = Permission_::where(array('name'=>$per_arr['name']))->get(); 
        //如果此权限已经存在
        if(!empty(count($permission))){
            return back()->with('alert_message', ['type' => 'error', 'message' =>  '此权限名已存在!']);
        }


        $inser_per=Permission_::create($per_arr);
        $inser_per->classify_belongsToMany()->sync($request->input('classify'));
        $details=new PermissionsDetails;
        $details->permission_id=$inser_per->id; 

        $permission =$details->where(array('permission_id'=>$inser_per->id))->get(); 
        $details->explain=$request->input('explain');

        if(!empty(count($permission))){
            $details->save();
        }else{
            $details->save();
        }

        dd( $details->permission_id);die;
        

        return redirect()->route('admin.permissions.index');
    }


    /**
     * Show the form for editing Permission.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if (! Gate::allows('update power')) {
            return abort(401);
        }
        $permission = Permission_::with(['classify_belongsToMany'])->findOrFail($id);

        $classify = ClassifyPermissions::where(array('parent_id'=>0))->orderBy('rank','DESC')->with(['classifyHasMany'])->get();
        
        return view('admin.manage.permissions.edit', compact('permission','classify'));
    }

    /**
     * Update Permission in storage.
     *
     * @param  \App\Http\Requests\UpdatePermissionsRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdatePermissionsRequest $request, $id)
    {
        if (! Gate::allows('update power')) {
            return abort(401);
        }


        $per_arr=$request->all();
        $classify_ids=$per_arr['classify'];
        unset($per_arr['classify']);
        
        $permission = Permission_::findOrFail($id);
        $permission->update($per_arr);
        $permission->classify_belongsToMany()->sync($request->input('classify'));




        return redirect()->route('admin.permissions.index');
    }


    /**
     * Remove Permission from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (! Gate::allows('users_manage')) {
            return abort(401);
        }
        $permission = Permission_::findOrFail($id);
        $permission->delete();

        return redirect()->route('admin.permissions.index');
    }

    /**
     * Delete all selected Permission at once.
     *
     * @param Request $request
     */
    public function massDestroy(Request $request)
    {
        if (! Gate::allows('users_manage')) {
            return abort(401);
        }
        if ($request->input('ids')) {
            $entries = Permission_::whereIn('id', $request->input('ids'))->get();

            foreach ($entries as $entry) {
                $entry->delete();
            }
        }
    }
  /**
     * Get a validator for an incoming change password request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'classify' => 'required',
        ]);
    }
}
